import requests
import json

from common.helper import get_request_url, get_request_headers


def list_documents():
    response = requests.get(
        url=get_request_url("v1/documents"),
        headers=get_request_headers(),
    )
    if response.status_code == 200:
        return json.loads(response.text)
    else:
        print(f"request failed<{response.status_code}>: {response.text}")
        raise Exception("request failed")


def traverse_files(data, title, current_path=""):
    if "items" not in data:
        return

    for item in data["items"]:
        if item["type"] == "file":
            if item['title'] == title:
                return f"{current_path}/{item['name']}"
            # # 处理文件
            # print(f"文件: {current_path}/{item['name']}")
            # print(f"ID: {item['id']}")
            # print(f"标题: {item['title']}")
            # print(f"URL: {item['url']}")
            # print(f"发布时间: {item['published']}")
            # print("-" * 50)
        elif item["type"] == "folder":
            # 递归处理文件夹
            new_path = f"{current_path}/{item['name']}" if current_path else item["name"]
            return traverse_files(item, title, new_path)


def filter_documents(title):
    available_documents = list_documents()
    test = traverse_files(available_documents["localFiles"], title=title)
    pass


if __name__ == "__main__":
    result = filter_documents("obsidian全平台同步方案.md")
    print(result)